package com.shujia.jinjie;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class MarioGame extends JPanel implements ActionListener {

    private Timer timer;
    private Mario mario;

    public MarioGame() {
        initGame();
    }

    private void initGame() {
        mario = new Mario();
        addKeyListener(new TAdapter());
        setFocusable(true);
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(800, 600));

        timer = new Timer(10, this);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        doDrawing(g);
    }

    private void doDrawing(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(mario.getImage(), mario.getX(), mario.getY(), this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        mario.move();
        repaint();
    }

    private class TAdapter extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {
            mario.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e) {
            mario.keyPressed(e);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Super Mario Game");
        MarioGame game = new MarioGame();
        frame.add(game);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}